package com.td.server;

import java.util.Iterator;

import com.td.core.messages.TDMessage;
import com.td.core.obj.Player;
import com.td.core.obj.TDGame;
import com.td.server.state.ActionState;
import com.td.server.state.BuildingState;
import com.td.server.state.State;

public class GameController {
	
	private int currentLevel = 0;
	private State currentState;
	
	private BuildingState buildingState;
	
	private ActionState actionState;
	
	private TDGame game;
	
	public GameController(TDGame game) {
		this.game = game;
		actionState = new ActionState(game);
		buildingState = new BuildingState(game);
		nextState();
	}
	
	public GameController(TDGame game, ActionState actionState, BuildingState buildingState) {
		this.game = game;
		this.actionState = actionState;
		this.buildingState = buildingState;
		nextState();
	}
	
	public void update() {
		
		if(currentState.isEnd()) {
			nextState();						
		}
		
		currentState.update();
		
		messagesUpdate();
	}
		
	private void messagesUpdate() {
		
		Player[] players = game.getPlayers();
		for(Player pl : players) {
			Iterator<TDMessage> it = pl.getMessages().iterator();
			while(it.hasNext()) {
				if(!it.next().update()) {		
					it.remove();
				}
			}
		}
	}

	private void nextState() {
		
		if(currentState instanceof BuildingState) {
			currentState = actionState;		
		} else if(currentState instanceof ActionState) {
			currentState = buildingState;
			currentLevel++;
		} else if(currentState == null) {
			currentState = buildingState;
			currentLevel++;
		}
		
		currentState.init(currentLevel);
		
		Player[] players = game.getPlayers();
			for(Player pl : players)
				pl.getStats().incrementLevel();
	}
	
	public boolean isGameEnded() {
		
		boolean end = true;
		
		Player[] players = game.getPlayers();
		for(Player pl : players) {
			end &= pl.isGameOver();
		}
		return end;
	}
}
